﻿/*******************************************************
 *  关卡列表 相关操作js
 * <p>Title: docManager.js</p>
 * <p>Description:TODO</p>
 * @author Joychen
 * @date 2019年8月5日 下午5:41:57
 * @version 1.0
 * *****************************************************/
var $table, unitzTree, options,//树控件
    selNode = null,//选中节点
    indexForm,
    checkNodeSpan = null;//选中树id;
var passManager = {
    //1.0 初始化页面
    initPage: function () {
        parent.showLoadBoxs();
        passManager.bindZtree();
        passManager.bindEvent();
        passManager.initTable();
        parent.delLoadBoxs();
    },
    //1.1 采用Ztree初始化文档树
    bindZtree: function () {
        var setting = {
            view: {
                showIcon: true,
                selectedMulti: false,
                fontCss: getFontCss
            },
            edit: {
                enable: true,
                showRemoveBtn: false,
                showRenameBtn: false
            },
            async: {
                enable: true,
                dataType: "text",
                type: "post",
                url: ctx + "/DocManager/GetDocTreeData?isNum=1&pro_type=3",
                autoParam: ["id"]
            },
            data: {
                key: { title: "name", name: "name" },
                simpleData: { enable: true, idKey: "id", pIdKey: "pId", rootPId: 0 }
            },
            check: {
                enable: false,
                autoCheckTrigger: true,
                chkStyle: "checkbox",
                chkboxType: { "Y": "p", "N": "ps" }
            },
            callback: {
                onAsyncError: function () {
                    layer.msg("初始化单位结构树失败~", { icon: 5 });
                },
                onAsyncSuccess: function (event, treeId, treeNode, msg) {
                    //树加载完成后执行
                    var obj = unitzTree.getNodes()[0];
                    if (obj) {
                        unitzTree.selectNode(obj);
                        unitzTree.setting.callback.onClick(null, unitzTree.setting.treeId, obj);//模拟点击事件 
                        if (obj.children && obj.children.length > 0)
                            unitzTree.expandNode(obj);
                    }
                },
                onClick: function (event, treeId, treeNode) {
                    //绑定课件下拉
                    if (!selNode || selNode.id != treeNode.id) 
                        passManager.bindClass(treeNode.id);
                    $('#unitTree a').css("color", "#333");
                    $('#' + treeNode.tId + '_a').css("color", "#ffffff");
                    checkNodeSpan = treeNode.tId + '_span';
                    selNode = treeNode;//选中节点
                    if ($table && treeNode.id > 0)
                        $table.bootstrapTable('refresh', options);//刷新Table
                }
            }
        };
        unitzTree = $("#unitTree").initzTreeView(setting, 'ushow');
    },
    //1.2 初始化Table
    initTable: function () {
        options = {
            url: ctx + "/HeadManager/InitPassTable",
            cutHeight: 50,
            showRefresh: false,
            showToggle: false,
            showColumns: false,
            singleSelect: false,//多选
            toolbar: "#exampleToolbar",
            queryParams: function (params) {
                params = {
                    rows: params.limit,
                    //页面大小  
                    page: params.offset / params.limit + 1,
                    keyword: $('#keyword').val(),
                    file_id: ($('#fileId').val()) ? $('#fileId').val() : 0,//课件id
                    folder_id: (selNode)?selNode.id:0,
                    folder_path: (selNode)?selNode.folder_path:""
                }
                return params;
            },
            columns:[
            {
                checkbox: true
            },{
                field: '',
                title: '序号',
                align: 'center',
                width: 120,
                formatter: function (value, row, index) {                     
                    return index + 1;
                }
            }, {
                field: 'file_name',
                title: '课件标题',
                align: 'center',
                formatter: function (value, row, index) {
                    if (value && value.toString().length > 10)
                        back = "<span title='" + value + "'>" + value.toString().substring(0, 10) + "...</span>";
                    else
                        back = value;
                    return back;
                }
            }, {
                field: 'cp_name',
                title: '关卡名称',
                align: 'left',
                formatter: function (value, row, index) {
                    if (value && value.toString().length > 10)
                        back = "<span title='" + value + "'>" + value.toString().substring(0, 10) + "...</span>";
                    else
                        back = value;
                    return back;
                }
            },{
                field: 'cp_code',
                title: '关卡代码',
                align: 'center'
            }, {
                field: 'wordCount',
                title: '单词数量',
                align: 'center'
            }, {
                field: 'update_name',
                title: '最后修改人',
                align: 'center'
            }, {
                field: 'update_date',
                title: '最后修改时间',
                align: 'center'
            }, {
                field: 'create_name',
                title: '创建人',
                align: 'center'
            }, {
                field: 'create_date',
                title: '创建时间',
                align: 'center'
            }],
            onClickRow: function (row, $element) {
            },
            onLoadSuccess: function (data) {
                //if (data && data.total > 0 && checkNodeSpan) {
                //    var val = $('#' + checkNodeSpan).text();
                //    if (val.indexOf('(') > -1)
                //        $('#' + checkNodeSpan).text(val.split('(')[0] + "(" + data.total + ")");
                //    else
                //        $('#' + checkNodeSpan).text(val + "(" + data.total + ")");
                //}
            }
        }
        $table = tableHelper.initTable("exampleTableToolbar", options);
    },
    //1.3 事件绑定
    bindEvent: function () {
        //查询
        $('#btnSearch').on('click',function () {
            var zTree = passManager.getSelNode();
            if (!zTree) {
                layer.msg("温馨提示：查询前请先选着目录节点！", { icon: 1 });
                return null;
            }
            $table.bootstrapTable('refresh', options);
        });
        //新增
        $('#btnAdd').on('click', function () {
            passManager.editForm();
        });
        //编辑
        $('#btnEditFile').on('click', function () {
            var row = passManager.selections();
            if (!row)
                return false;
            passManager.editForm(row);
        });
        //删除
        $('#btnDeleteFile').on('click', function () {
            var row = passManager.selections(true);
            if (!row)
                return false;
            layer.confirm('您确定要删除当前选择关卡？', {
                btn: ['确定', '取消'] //按钮
            }, function () {
                var index = layer.msg("删除中...", { icon: 6, time: 6000 });
                var cpID = new Array();
                $.each(row, function (index, item) {
                    cpID.push(item.cp_id);
                });
                $.ajax({
                    type: 'post',
                    url: ctx + '/HeadManager/DelCustomPass' ,
                    dataType: 'json',
                    data: { cp_id: cpID.join(',') },
                    async: false,
                    success: function (data) {
                        if (index)
                            layer.close(index);
                        if (data.Statu === 0) {
                            layer.msg("删除成功...");
                            $table.bootstrapTable('refresh');
                        }
                        else
                            layer.alert(data.Msg, { icon: 5 });
                    }
                });
            }, function () { });
        });
        //移动关卡
        $('#btnMove').on('click', function () {
            //收集需要移动的单词
            var row = passManager.selections(true);
            if (!row)
                return false;
            var fileId = $('#fileClass').val();
            if (!fileId) {
                layer.msg("请选择需要移动的课件！");
                return false;
            }
            var fileVal = $('#fileClass').find("option:selected").text();
            var cpID = new Array();
            $.each(row, function (index, item) {
                cpID.push(item.cp_id);
            });
            var layerIndex = layer.msg('数据处理中...', { icon: 16, shade: [0.3, '#393D49'], time: 0 });
            layer.confirm('您确定要移动当前选中关卡至：' + fileVal+' 课件中吗？', {
                btn: ['确定', '取消'] //按钮
            }, function () {
                $.ajax({
                    type: 'post',
                    url: ctx + '/HeadManager/MovePass',
                    dataType: 'json',
                    async: false,
                    data: { file_id: fileId, file_name: fileVal, cp_id: cpID },
                    success: function (data) {
                        layer.close(layerIndex);
                        if (data.Statu === 0) {
                            $table.bootstrapTable('refresh', options);
                            layer.msg("关卡移动成功！", { icon: 1 });
                        }
                        else
                            layer.msg(data.Msg, { icon: 5 });
                    }
                });
            }, function () { });
        });
    },
    //1.4 获取被选中节点
    getSelNode: function () {
        //获取页面doc_type参数
        //获取节点folder_id参数
        var zTree = $.fn.zTree.getZTreeObj("unitTreezTreeData");
        if (!zTree)
            return null;
        var nodes = zTree.getSelectedNodes(),
           treeNode = nodes[0];
        return treeNode;
    },
    //1.5 获取被选中节点
    selections: function (isAll) {
        var row = $table.bootstrapTable('getSelections');
        if (!row || row.length === 0) {
            layer.msg("数据为空或未选中记录行~", { icon: 5 });
            return false;
        }
        if (isAll)
            return row;
        if (row.length > 1) {
            layer.msg("当前操作不支持多选，请选择一行再操作！", { icon: 5 });
            return false;
        }
        return row[0];
    },
    //1.6 添加、编辑
    editForm: function (row) {
        var $title = "添加关卡";
        if (!row)
            addOrEditUrl = ctx + "/HeadManager/AddCustomPass";//新增
        else {
            addOrEditUrl = ctx + "/HeadManager/EditCustomPass";//编辑
            $title = "编辑关卡";
        }
        //清空表单
        $('#orgFormTable').resetHideValidForm();
        //打开编辑
        layer.open({
            title: [$title, 'font-size:18px;'],
            type: 1,
            content: $('#org_form'),
            scroll: true,//是否显示滚动条、默认不显示
            btn: ['确定', '取消'],
            area: ['480px', '400px'],
            success: function (li, o) {
                $('#file_id').selectpicker('refresh');
                if (row != null) {
                    $('#orgFormTable')[0].reset();//重置表单
                    $('#orgFormTable').LoadForm(row);//表单填充数据
                }
            },
            yes: function (li, o) {
                //判断课件
                var file_id = $('#file_id').val();
                if (!file_id) {
                    layer.msg("请选择课件！");
                    return false;
                }
                var fileName = $('#file_id').find("option:selected").text();
                if (fileName.indexOf("【") > -1)
                    fileName = fileName.substring(0, fileName.indexOf("【"));
                $('#file_name').val(fileName);
                if ($('#orgFormTable').valid()) {
                    //验证通过
                    $('#orgFormTable').ajaxSubmit({
                        url: addOrEditUrl,
                        type: "post",

                        dataType: "json",
                        beforeSubmit: function (arr, $form, options) {
                            layer.msg("提交数据~", { icon: 1, time: 5000 });
                        },
                        success: function (result, status, xhr, $form) {
                            if (result.Statu === 0) {
                                layer.closeAll();
                                $table.bootstrapTable('refresh', options);
                                layer.msg('保存成功', { icon: 1 });
                            }
                            else
                                layer.alert(result.Msg, { icon: 5 });
                        },
                        error: function (xhr, status, error, $form) {
                            layer.msg("保存失败~", { icon: 5 });
                        }
                    });
                }
            },
            cancel: function (li, o) {

            }
        });
    },
    //1.7 绑定课件下拉
    bindClass: function (folder_id) {
        $.ajax({
            type: 'post',
            url: ctx + '/HeadManager/GetClassInfo/' + folder_id,
            dataType: 'json',
            data:{notStatus:2}, //数据没有实际意义，仅仅表示大于0 需要排除审核未通过的记录
            async: false,
            success: function (data) {
                if (data.Statu === 0) {
                    var itemStr = "", fileStr = "<option value='' selected=''>全部课件</option>";
                    $.each(data.Data, function (i, item) {
                        if (i === 0)
                            itemStr += "<option value='" + item.value + "' selected=''>" + item.text + "</option>";
                        else
                            itemStr += "<option value='" + item.value + "'>" + item.text + "</option>";
                        fileStr += "<option value='" + item.value + "'>" + item.text + "</option>";
                    });
                    //判断导入按钮是否可用
                    if (data.Data && data.Data.length > 0){
                        $('#btnAdd').removeAttr("disabled");
                    }
                    else {
                        $('#btnAdd').attr("disabled", "disabled");
                    }
                    //添加时课件下拉
                    $("#file_id").empty();
                    $('#file_id').selectpicker('refresh');
                    $('#file_id').append(itemStr);
                    $('#file_id').selectpicker('refresh');
                    //查询时课件下拉
                    $("#fileId").empty();
                    $('#fileId').selectpicker('refresh');
                    $('#fileId').append(fileStr);
                    $('#fileId').selectpicker('refresh');
                }
                else
                    layer.msg(data.Msg, { icon: 5 });
            }
        });
        //绑定移动课件下拉
        $.ajax({
            type: 'post',
            url: ctx + '/HeadManager/GetClassInfo/' + folder_id,
            dataType: 'json',
            data: { fileStatus: 5 },
            async: false,
            success: function (data) {
                if (data.Statu === 0) {
                    var itemStr = "";
                    $.each(data.Data, function (i, item) {
                        itemStr += "<option value='" + item.value + "'>" + item.text + "</option>";
                    });
                    //移动课件选择
                    $("#fileClass").empty();
                    $('#fileClass').selectpicker('refresh');
                    $('#fileClass').append(itemStr);
                    $('#fileClass').selectpicker('refresh');
                }
                else
                    layer.msg(data.Msg, { icon: 5 });
            }
        });
    }
}